<template>
  <div class="roles">

    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="isShowAddDiaglose = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 信息展示 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand" style="padding: 50px 20px;">
          <template v-slot="scoped">
            <el-row v-for="(item1, i1) in scoped.row.children" :key="item1.id"
              :class="['vcenter', 'bdtop', i1 === 0 ? 'bdbottom' : '']">

              <!-- 一级标签 -->
              <el-col :span="5">
                <el-tag closable @close="deleteRight(scoped.row, item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <!-- 二,三级标签 -->
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id"
                  :class="['vcenter', i2 == 0 ? '' : 'bdtop']">

                  <!-- 二级标签 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteRight(scoped.row, item2.id)">{{ item2.authName
                    }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 三级标签 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable
                      @close="deleteRight(scoped.row, item3.id)">{{
                        item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column prop="address" label="操作">
          <template v-slot="scoped">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" @click="getEditRole(scoped.row.id)">编辑</el-button>

            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" @click="deleteRole(scoped.row.id)">删除</el-button>

            <!-- 分配角色按钮 -->
            <el-button type="warning" icon="el-icon-setting" @click="setRightsDialog(scoped.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色表格 -->
    <el-dialog title="添加角色" :visible.sync="isShowAddDiaglose" width="50%" @close="addRolesDialogClose">

      <!-- 表格填入 -->
      <el-form ref="addRolesFormRef" :model="addRolesList" label-width="80px" :rules="addRolesRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <!-- 表格操作 -->
      <span slot="footer">
        <el-button @click="isShowAddDiaglose = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色表格 -->
    <el-dialog title="提示" :visible.sync="isShowEditDiaglose" width="50%" @close="editRolesDialogClose">

      <!-- 表格填入 -->
      <el-form ref="editRolesFormRef" :model="editRoleList" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="editRoleList.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleList.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <!-- 表格操作 -->
      <span slot="footer">
        <el-button @click="isShowEditDiaglose = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限表格 -->
    <el-dialog title="提示" :visible.sync="isShowSetRightsDiaglose" width="50%" @close="setRoleRightsDialogClose">

      <!-- 展示内容 -->
      <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
        :default-checked-keys="roleRights" ref="setRightsRef"></el-tree>

      <!-- 控件区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowSetRightsDiaglose = false">取 消</el-button>
        <el-button type="primary" @click="setRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      addRolesList: {},
      editRoleList: {},
      rightsList: [], // 所有权限列表
      isShowAddDiaglose: false,
      isShowEditDiaglose: false,
      isShowSetRightsDiaglose: false,
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      },
      // el-tree的配置项
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      roleRights: [], // 用户权限ID列表
      roleID: '' // 当前用户的ID
    }
  },
  methods: {

    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.rolesList = res.data
    },

    // 添加角色
    addRoles () {
      this.$refs.addRolesFormRef.validate(async (valid) => {
        if (!valid) return this.message.error('请将信息填写完整')
        const { data: res } = await this.$http.post('roles', this.addRolesList)
        if (res.meta.status !== 201) return this.$message.error('修改失败')
        this.getRolesList()
        this.$message.success('修改成功')
        this.isShowAddDiaglose = false
      })
    },

    // 关闭添加角色框触发
    addRolesDialogClose () {
      this.$refs.addRolesFormRef.resetFields()
    },
    editRolesDialogClose () {
      this.$refs.editRolesFormRef.resetFields()
    },
    setRoleRightsDialogClose () {
      this.roleRights = []
    },
    // 删除角色
    deleteRole (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { data: res } = this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getRolesList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 获取需要编辑的角色
    async getEditRole (id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取用户失败')
      this.editRoleList = res.data
      this.isShowEditDiaglose = true
    },

    // 编辑角色
    editRole () {
      this.$refs.editRolesFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请将信息填写完整')
        const { data: res } = await this.$http.put(`roles/${this.editRoleList.roleId}`, { roleName: this.editRoleList.roleName, roleDesc: this.editRoleList.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.getRolesList()
        this.isShowEditDiaglose = false
      })
    },

    // 删除角色权限
    deleteRight (role, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        role.children = res.data
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 打开分配角色权限窗口
    async setRightsDialog (role) {
      this.isShowSetRightsDiaglose = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.message.error('获取权限列表失败')
      this.rightsList = res.data
      this.getAllID(role, this.roleRights)
      this.roleID = role.id
    },

    // 递归获取元素的所有第三级权限ID
    getAllID (node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => {
        this.getAllID(item, arr)
      })
    },

    // 提交分配的权限
    async setRights () {
      const nowRights = [
        ...this.$refs.setRightsRef.getHalfCheckedKeys(),
        ...this.$refs.setRightsRef.getCheckedKeys()
      ]
      const postArr = nowRights.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleID}/rights`, { rids: postArr })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('修改成功')
      this.isShowSetRightsDiaglose = false
      this.getRolesList()
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>

<style>
.el-tag {
  margin: 7px;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.bdtop {
  border-top: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
